<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ViewGetYears as ViewGetYearsModel;
use app\common\model\ViewGetSeasons as ViewGetSeasonsModel;
use app\common\model\ViewGetDepts as ViewGetDeptsModel;
use app\common\model\ViewGetTeacherSpecicalties as ViewGetTeacherSpecicaltiesModel;
use app\common\model\ViewGetTeacherClasses as ViewGetTeacherClassesModel;
use app\common\model\ViewGetDirs as ViewGetDirsModel;
use app\common\model\ViewGetTeachers as ViewGetTeachersModel;
use app\common\model\user as userModel;
use app\common\model\StudentExceptInfo as StudentExceptInfoModel;
use app\common\model\Config as ConfigModel;
use app\common\model\BookApply as BookApplyModel;
use app\common\model\BookApplyDetail as BookApplyDetailModel;
use app\common\model\BookDraw as BookDrawModel;
use app\common\model\AssistantUserRel as AssistantUserRelModel;
use app\common\model\BookAccount as BookAccountModel;

use app\common\model\Common;
use think\console\output\descriptor\Console;
use think\Db;
use think\facade\Log;

class Book extends Api
{
    /**
     * 获取年份
     * @return array
     */
    public function getYears()
    {
        $viewGetYearsModel = new ViewGetYearsModel();
        $list = $viewGetYearsModel->tableData([]);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }

    /**
     * 获取季度
     * @return array
     */
    public function getSeasons()
    {
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $list = $viewGetSeasonsModel->tableData([]);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取部门
     * @return array
     */
    public function getDepts()
    {
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $list = $viewGetDeptsModel->tableData([]);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取专业
     * @return array
     */
    public function getSpecicalties()
    {
        // 这里要取辅导员的关联专业
        
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        // 如果自己是助手查询辅导员负责的记录 
        $id = $this->userId; 
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrId = $user->getUserIdByMobile($relInfo['userMobile']);
            $id = $id . ', ' . $mgrId;
        }

        $where['id'] = $id;

        $list = $userInfo = $user->getSpecicalties($where);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取班级
     * @return array
     */
    public function getClasses()
    {
        // 这里要获取辅导员的关联班级
        $zydm  = input('param.zydm', '');     // 搜索关键字
        
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        // 如果自己是助手查询辅导员负责的记录
        
        $id = $this->userId; 
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrId = $user->getUserIdByMobile($relInfo['userMobile']);
            $id = $id . ', ' . $mgrId;
        }

        $where['id'] = $id;
        $where['zydm'] = $zydm; 
        
        $list = $userInfo = $user->getClasses($where);

        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取方向
     * @return array
     */
    public function getDirs()
    {
        $viewGetDirsModel = new ViewGetDirsModel();
        $list = $viewGetDirsModel->tableData([]);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取辅导员
     * @return array
     */
    public function getTeachers()
    {
        $viewGetTeachersModel = new ViewGetTeachersModel();
        $list = $viewGetTeachersModel->tableData([]);
        
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }

    /**
     * 获取申请班级列表
     * @return array
     */
    public function getApplyClassList()
    { 
        $zydm  = input('param.zydm', '');     // 搜索关键字
        $bjdm  = input('param.bjdm', '');     // 搜索关键字
        $dir  = input('param.dir', '');     // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);

        // 查询自己负责的记录
        $model = new Common();
        $list = $model->query("call programApplyClassList('".$dir."','".$bjdm."','".$zydm."','".$userInfo['mobile']."');");
        
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $Mgrlist = $model->query("call programApplyClassList('".$dir."','".$bjdm."','".$zydm."','".$mgrMobile."');");
            
            if(count($Mgrlist) > 0) {
                foreach($Mgrlist[0] as $key => $val) {
                    $list[0][] = $val;
                }
            }
        }
        
        if(count($list) > 0){
            $result = [
                'status' => true,
                'data'   => $list[0],
                'msg'    => '查询成功'
            ];
        } else {
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '无记录'
            ];
        }
  
        return $result;
    }

    /**
     * 获取申请记录
     * @return array
     */
    public function getApplyLogList()
    {
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);

        // 查询自己负责的记录
        $model = new Common();
        $list = $model->query("call programApplyLogList('".$userInfo['mobile']."');");
        
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $Mgrlist = $model->query("call programApplyLogList('".$mgrMobile."');");
            
            if(count($Mgrlist) > 0) {
                foreach($Mgrlist[0] as $key => $val) {
                    $list[0][] = $val;
                }
            }
        }
        
        if(count($list) > 0){
            $result = [
                'status' => true,
                'data'   => $list[0],
                'msg'    => '查询成功'
            ];
        } else {
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '无记录'
            ];
        }
  
        return $result;
    }

    /**
     * 获取申请班级明细
     * @return array
     */
    public function getBookAplyDetail()
    { 
        $plan_class_id  = input('param.plan_class_id', '');     // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        
        // 查询自己负责的记录
        $model = new Common();
        $list = $model->query("call programApplyDetail('".$plan_class_id."','".$userInfo['mobile']."');");
        
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $Mgrlist = $model->query("call programApplyDetail('".$plan_class_id."','".$mgrMobile."');");

            if(count($Mgrlist) > 0) {
                foreach($Mgrlist[0] as $key => $val) {
                    $list[0][] = $val;
                }
            }
        }

        // 判断班级有几个老师
        $teacherList = $model->query("call getClassTeacherList('".$plan_class_id."');");

        if(count($list) > 0){
            $result = [
                'status'    => true,
                'data'      => $list[0],
                'teacherList'=> $teacherList[0],
                'msg'       => '查询成功'
            ];
        } else {
            $result = [
                'status'    => false,
                'data'      => [],
                'teacherList'=> [],
                'msg'       => '无记录'
            ];
        }
   
        return $result;
    }
    
    /**
     * 获取申请日志班级明细
     * @return array
     */
    public function getBookAplyLogDetail()
    { 
        $plan_class_id  = input('param.plan_class_id', '');     // 搜索关键字
        $applyId  = input('param.id', '');                           // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        
        $model = new Common();
        // 查询自己负责的记录
        $list = $model->query("call programApplyLogDetail('".$applyId."');");
        // 获取班级内未申请的学生列表
        $studentList = $model->query("call programApplyDetail('".$plan_class_id."','".$userInfo['mobile']."');");
        
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $studentMgrlist = $model->query("call programApplyDetail('".$plan_class_id."','".$mgrMobile."');");

            if(count($studentMgrlist) > 0) {
                foreach($studentMgrlist[0] as $key => $val) {
                    $studentList[0][] = $val;
                }
            }
        } 

        $student = [];
        if(count($studentList) > 0) {
            foreach($studentList[0] as $key => $val) {
                if($val['sdzt'] == 0) {
                    $student[] = $val;
                }
            }
        }

        $config = new ConfigModel();

        $data = input('param.');
        $currYear = $config->getYear();
        $currSeason= $config->getSeason();

        if(count($list) > 0){
            if(count($studentList) > 0) {
                $result = [
                    'status'    => true,
                    'data'      => $list[0],
                    'studentList'=> $student,
                    'currYear'  => $currYear,
                    'currSeason'  => $currSeason,
                    'msg'       => '查询成功'
                ];
            } else {
                $result = [
                    'status'    => true,
                    'data'      => $list[0],
                    'studentList'=> [],
                    'currYear'  => $currYear,
                    'currSeason'  => $currSeason,
                    'msg'       => '查询成功'
                ];
            }
        } else {
            $result = [
                'status'    => false,
                'data'      => [],
                'studentList'=> [],
                'currYear'  => $currYear,
                'currSeason'  => $currSeason,
                'msg'       => '无记录'
            ];
        }
   
        return $result;
    }

    /**
     * 锁定
     * @return array
     */
    public function studentlock()
    { 
        $config = new ConfigModel();

        $data = input('param.');
        $data['teacher'] = $this->userId;
        $data['year'] = $config->getYear();
        $data['season'] = $config->getSeason();

        // 查询学生清单  
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrId = $userInfo->getUserIdByMobile($relInfo['userMobile']);
            $data['teacher'] = $mgrId;
        }

        $studentExceptInfoModel = new StudentExceptInfoModel();
        return $studentExceptInfoModel->addData($data);
    }

    /**
     * 解锁
     * @return array
     */
    public function studentunlock()
    { 
        $config = new ConfigModel();

        $data = input('param.');
        $data['teacher'] = $this->userId;
        $data['year'] = $config->getYear();
        $data['season'] = $config->getSeason();

        // 查询学生清单  
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrId = $userInfo->getUserIdByMobile($relInfo['userMobile']);
            $data['teacher'] = $mgrId;
        }

        $studentExceptInfoModel = new StudentExceptInfoModel();
        return $studentExceptInfoModel->del($data);
    }

    /**
     * 提交请求
     * @return array
     */
    public function bookApply()
    {
        $result = [
            'status' => true,
            'msg'    => '申请成功',
            'data'   => [],
        ];

        $plan_class_ids  = input('param.plan_class_ids', '');     // 搜索关键字
        $class_ids = explode(',', $plan_class_ids);

        // 查询学生清单  
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        
        $config = new ConfigModel(); 

        $bookApply = new BookApplyModel();
        $bookApplyDetail = new BookApplyDetailModel();

        for ($i = 0; $i < count($class_ids); $i++) {
            if ($class_ids[$i]) {
                $model = new Common();
                $list = $model->query("call programApplyDetail('".$class_ids[$i]."','".$userInfo['mobile']."');");
                
                // 如果自己是助手查询辅导员负责的记录
                $relModel = new AssistantUserRelModel();
                $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
                if($relInfo) {
                    $mgrMobile = $relInfo['userMobile'];
                    $Mgrlist = $model->query("call programApplyDetail('".$class_ids[$i]."','".$mgrMobile."');");

                    if(count($Mgrlist) > 0) {
                        foreach($Mgrlist[0] as $key => $val) {
                            $list[0][] = $val;
                        }
                    }
                }

                // 生成学生清单
                $students = [];
                //$studentIds = "";
                
                for ($j = 0; $j < count($list[0]); $j++) {
                    if($list[0][$j]['sdzt'] == '0'){
                        $students[] = $list[0][$j];
                        //$studentIds .= $list[0][$i]['xh'] . ",";
                    }
                }

                // 判断你是否有未发放的数据
                // 重复提交判定
                $applyExistWhere = []; 
                $applyExistWhere[] = ['year', 'eq', $config->getYear()]; 
                $applyExistWhere[] = ['season', 'eq', $config->getSeason()]; 
                $applyExistWhere[] = ['class_id', 'eq', $class_ids[$i]]; 
                $applyExistWhere[] = ['is_ff', 'eq', '0']; 
                
                $studentExistInfo = $bookApply->field('id, num')
                    ->where($applyExistWhere)
                    ->find();
                
                if(count($students) > 0) {
                    if($studentExistInfo) { 
                        $applyId = $studentExistInfo['id'];
                        $applyNum = $studentExistInfo['num'] + count($students);
                        Db::startTrans();
                        // 更新数量
                        $res = $bookApply->allowField(true)->save(['num'=>$applyNum],['id'=>$applyId]);
                        if (!$res)
                        {
                            $result['status'] = false;
                            $result['msg'] = '申请失败';
                            Db::rollback();
                            return $result;
                        } else {
                            $item     = [];
                            // 生成申请明细
                            for ($j = 0; $j < count($students); $j++) {
                                if ($students[$j]) {
                                    $item[] = [
                                        'applyid'   => $applyId,
                                        'xh'        => $students[$j]['xh'],
                                        'xm'        => $students[$j]['xm'],
                                    ];
                                }
                            }

                            if (!$bookApplyDetail->saveAll($item)) {
                                $result['status'] = false;
                                $result['msg'] = '申请明细提交失败，请重试';
                                Db::rollback();
                                return $result;
                            }
                        }
                        Db::commit();
                    } else {
                        // 生成申请记录
                        $data = [];
                        $data['teacherid'] = $this->userId;
                        $data['year'] = $config->getYear();
                        $data['season'] = $config->getSeason();
                        $data['time'] = time();
                        $data['num'] = count($students);
                        $data['dep_id'] = $students[0]['plan_dep_id'];
                        $data['specialty_id'] = $students[0]['plan_specialty_id'];
                        $data['class_id'] = $students[0]['plan_class_id'];
                        $data['grade'] = $students[0]['plan_grade'];
                        $data['dir'] = $students[0]['plan_dir'];

                        Db::startTrans();
                        $res = $bookApply->allowField(true)->insert($data);
                        if (!$res)
                        {
                            $result['status'] = false;
                            $result['msg'] = '申请失败';
                            Db::rollback();
                            return $result;
                        } else {
                            $applyid = $bookApply->getLastInsID(); 
                            $item     = [];
                            // 生成申请明细
                            for ($j = 0; $j < count($students); $j++) {
                                if ($students[$j]) {
                                    $item[] = [
                                        'applyid'   => $applyid,
                                        'xh'        => $students[$j]['xh'],
                                        'xm'        => $students[$j]['xm'],
                                    ];
                                }
                            }

                            if (!$bookApplyDetail->saveAll($item)) {
                                $result['status'] = false;
                                $result['msg'] = '申请明细提交失败，请重试';
                                Db::rollback();
                                return $result;
                            }
                        }
                        Db::commit();
                    }
                }
            }
        }
        
        return $result;
    }

    /**
     * 获取学生信息
     * @return array
     */
    public function getStudentInfo()
    {
        $key  = input('param.key', '');     // 搜索关键字
 
        $userModel = new userModel();
        $userInfo = $userModel->getUserInfo($this->userId);

        // 如果自己是助手查询辅导员负责的记录
        $mobile = $userInfo['mobile'];
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mobile = $relInfo['userMobile'];
        }

        $model = new Common();
        $list = $model->query("call programStudentInfo('".$key."', '".$mobile."');");
        
        if(count($list) > 0){
            $result = [
                'status' => true,
                'data'   => $list[0],
                'msg'    => '查询成功'
            ];
        } else {
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '无记录'
            ];
        }

        return $result;
    } 

    /**
     * 教材个人发放
     * @return array
     */
    public function bookDraw()
    {
        $xh  = input('param.xh', '');     // 学号
        $xm  = input('param.xm', '');     // 姓名
        $bmdm  = input('param.bmdm', '');     // 学院编号
        $zydm  = input('param.zydm', '');     // 专业编号
        $plan_class_id  = input('param.plan_class_id', '');     // 班级编号
        $dir  = input('param.dir', '');     // 方向
        $platform  = input('param.platform', '');     // 平台
   
        $config = new ConfigModel();
        $year = $config->getYear();
        $season = $config->getSeason();

        $userModel = new userModel();
        $userInfo = $userModel->getUserInfo($this->userId);

        // 判断是否已经锁定
        $studentExceptInfoModel = new StudentExceptInfoModel();

        // 如果自己是助手查询辅导员负责的记录
        $id[] = $this->userId; 
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrId = $userModel->getUserIdByMobile($relInfo['userMobile']);
            $id[] = $mgrId;
        }
  
        $exceptWhere = [];
        $exceptWhere[] = ['xh', 'eq', $xh];
        $exceptWhere[] = ['year', 'eq', $year];
        $exceptWhere[] = ['season', 'eq', $season];
        $exceptWhere[] = ['teacher', 'in', $id];
        $bookDrawInfo = $studentExceptInfoModel->where($exceptWhere)->find();
        if($bookDrawInfo){
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '该学生已锁定'
            ];
            return $result;
        }

        // 判断是否已经领取过
        $bookDraw = new BookDrawModel(); 
        $isDrawWhere = [];
        $isDrawWhere[] = ['xh', 'eq', $xh];
        $isDrawWhere[] = ['draw_year', 'eq', $year];
        $isDrawWhere[] = ['draw_season', 'eq', $season];
        $bookDrawInfo = $bookDraw->where($isDrawWhere)->find();
        if($bookDrawInfo){
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '该学生已经签收了教材！'
            ];
            return $result;
        }

        // 判断班级是否有书
        // 1、该学生是否参与批量领书，且处于尚未发放状态
        $bookApply = new BookApplyModel();
        if(!$bookApply->studentIsReady($year, $season, $xh)){
            // 2、所在班级是否有预发放教材
            $classBatchDrawInfo = [];
            // 如果自己是助手查询辅导员负责的记录
            $id[] = $this->userId; 
            $relModel = new AssistantUserRelModel();
            $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
            if($relInfo) {
                $classBatchDrawInfo = $bookApply->query("call getClassBatchDrawInfo('".$plan_class_id."','".$relInfo['userMobile']."');");
            } else {
                $classBatchDrawInfo = $bookApply->query("call getClassBatchDrawInfo('".$plan_class_id."','".$userInfo['mobile']."');");
            }
            
            if($classBatchDrawInfo && count($classBatchDrawInfo) > 0) {
                if($classBatchDrawInfo[0][0]['ffrs'] <= $classBatchDrawInfo[0][0]['qsrs']){
                    $result = [
                        'status' => false,
                        'data'   => [],
                        'msg'    => '该班级还未领书，请先去教材公司领书！'
                    ];
                    return $result;
                }
            } else {
                $result = [
                    'status' => false,
                    'data'   => [],
                    'msg'    => '该班级还未领书，请先去教材公司领书！'
                ];
                return $result;
            }
        }
        
        $bookApplyDetail = new BookApplyDetailModel();
        $studentApplyInfo = $bookApplyDetail->getStudentApplyInfo($year, $season, $xh);
        $grade = '';
        if($studentApplyInfo) {
            $detailId = $studentApplyInfo['id'];
            $grade = $studentApplyInfo['grade'];
            $bookApplyDetail->save(['is_qs' => '1'], ['id' => $detailId]);
        }

        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        $mgrID = $this->userId;
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $mgrID = $userModel->getUserIdByMobile($mgrMobile);
        }

        // 增加领取记录
        $iData = [
            'xh'                => $xh,
            'draw_school_id'    => '',
            'draw_institute_id' => '',
            'draw_dep_id'       => $bmdm,
            'draw_specialty_id' => $zydm,
            'draw_class_id'     => $plan_class_id,
            'draw_grade'        => $grade,
            'draw_dir'          => $dir,
            'draw_year'         => $year,
            'draw_season'       => $season,
            'draw_operid'       => $this->userId,
            'draw_date'         => time(),
            'draw_remark'       => '',
            'draw_mgrid'        => $mgrID
        ];
        $bookDraw->save($iData);
 
        $result = [
            'status' => true,
            'data'   => [],
            'msg'    => '领取成功'
        ];

        return $result;
    } 
    
    /**
     * 获取管理员所负责的管理员信息
     * @return array
     */
    public function getBookMgrOperatorsInfo()
    {
        $platform  = input('param.platform', 1);      // 1就是h5登录（h5端和微信公众号端），2就是微信小程序登录，3是支付宝小程序，4是app，5是pc
        
        $sql = "select '0' id, '全部管理员' truename 
                union select id, truename from zl_user a where id = '" . $this->userId . "'
                union select c.id, c.truename from zl_user a, zl_assistant_user_rel b, zl_user c where a.id = '" . $this->userId . "' and a.mobile = b.userMobile and b.assistantUserMobile = c.mobile";

        $list = Db::query($sql);
        if (!$list || count($list) == 0) {
            return error_code(20101);
        }
 
        $result = [
            'status' => true,
            'data'   => $list,
            'msg'    => '查询成功'
        ];

        return $result;
    }

    /**
     * 根据管理员、时间获取教材发放清单
     * @return array
     */
    public function getBookDrawInfo()
    {
        $platform  = input('param.platform', 1);      // 1就是h5登录（h5端和微信公众号端），2就是微信小程序登录，3是支付宝小程序，4是app，5是pc
        $operator  = input('param.operator', '');     // 搜索关键字
        $all = input('param.all', '');          // 搜索关键字
        $date  = input('param.date', '');             // 搜索关键字
        
        // 如果日期不存在返回错误
        if ($date == '') {
            return error_code(20102);
        }

        // 日期检测
        $times = explode("-", $date);
        if(count($times) != 3) {
            return error_code(20102);
        }

        if(strlen($times[1]) == 1) {
            $times[1] = "0" . $times[1];
        }

        if(strlen($times[2]) == 1) {
            $times[2] = "0" . $times[2];
        }

        $config = new ConfigModel();
        $currYear = $config->getYear();
        $currSeason = $config->getSeason();

        $date = $times[0].'-'.$times[1].'-'.$times[2];
        $sqlAll = '';
        if($all == '1') {
            $sqlAll = "select * From zl_book_draw where draw_year = '".$currYear."' and draw_season = '".$currSeason."' and (draw_operid in ('".$operator."') or draw_mgrid = '".$this->userId."')";
        } else {
            $sqlAll = "select * From zl_book_draw where draw_year = '".$currYear."' and draw_season = '".$currSeason."' and draw_operid in ('".$operator."')";
        }
        
        $listAll = Db::query($sqlAll);

        $sqlQuery = "";
        if($all == '1') {
            $sqlQuery = "select A.id, c.truename, B.XH, B.XM, substr(FROM_UNIXTIME(draw_date), 12, 8) LQSJ 
                From zl_book_draw a, zlzhsf.pxsdm b, zl_user c 
                where a.xh = b.xh and a.draw_year = '".$currYear."' and a.draw_season = '".$currSeason."' and a.draw_operid = c.id and substr(FROM_UNIXTIME(draw_date), 1, 10) = '".$date."' and (draw_operid in ('".$operator."') or draw_mgrid = '".$this->userId."') 
                order by draw_date, xh";
        } else {
            $sqlQuery = "select A.id, c.truename, B.XH, B.XM, substr(FROM_UNIXTIME(draw_date), 12, 8) LQSJ 
            From zl_book_draw a, zlzhsf.pxsdm b, zl_user c 
            where a.xh = b.xh and a.draw_year = '".$currYear."' and a.draw_season = '".$currSeason."' and a.draw_operid = c.id and substr(FROM_UNIXTIME(draw_date), 1, 10) = '".$date."' and draw_operid in ('".$operator."')
            order by draw_date, xh";
        }

        $listQuery = Db::query($sqlQuery);

        $data = [
            'allNum' => count($listAll),
            'num' => count($listQuery),
            'list' => $listQuery
        ];

        $result = [
            'status' => true,
            'data'   => $data,
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取待签收班级列表
     * @return array
     */
    public function getDrawClassList()
    { 
        $zydm  = input('param.zydm', '');     // 搜索关键字
        $bjdm  = input('param.bjdm', '');     // 搜索关键字
        $dir  = input('param.dir', '');     // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);

        $model = new Common();
        $list = $model->query("call programDrawClassList('".$dir."','".$bjdm."','".$zydm."','".$userInfo['mobile']."');");
        
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $Mgrlist = $model->query("call programDrawClassList('".$dir."','".$bjdm."','".$zydm."','".$mgrMobile."');");

            if(count($Mgrlist) > 0) {
                foreach($Mgrlist[0] as $key => $val) {
                    $list[0][] = $val;
                }
            }
        }
        
        if(count($list) > 0){
            $result = [
                'status' => true,
                'data'   => $list[0],
                'msg'    => '查询成功'
            ];
        } else {
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '无记录'
            ];
        }

        return $result;
    }

    /**
     * 获取待签收班级明细
     * @return array
     */
    public function getDrawConfirmDetail()
    { 
        $plan_year  = input('param.plan_year', '');     // 搜索关键字
        $plan_season  = input('param.plan_season', '');     // 搜索关键字
        $plan_class_id  = input('param.plan_class_id', '');     // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        
        $model = new Common();
        $list = $model->query("call programDrawConfirmDetail('".$plan_year."','".$plan_season."','".$plan_class_id."','".$userInfo['mobile']."');");
     
        // 如果自己是助手查询辅导员负责的记录
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $Mgrlist = $model->query("call programDrawConfirmDetail('".$plan_year."','".$plan_season."','".$plan_class_id."','".$mgrMobile."');");

            if(count($Mgrlist) > 0) {
                foreach($Mgrlist[0] as $key => $val) {
                    $list[0][] = $val;
                }
            }
        }

        if(count($list) > 0){
            $result = [
                'status' => true,
                'data'   => $list[0],
                'msg'    => '查询成功'
            ];
        } else {
            $result = [
                'status' => false,
                'data'   => [],
                'msg'    => '无记录'
            ];
        }

        return $result;
    }
    
    /**
     * 班级批量签收
     * @return array
     */
    public function bookListDraw()
    { 
        $result = [
            'status' => true,
            'msg'    => '签收成功',
            'data'   => [],
        ];

        $plan_class_ids  = input('param.plan_class_ids', '');     // 搜索关键字
        $class_ids = explode(',', $plan_class_ids);

        // 查询学生清单  
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId); 
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        $mgrID = $this->userId;
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $mgrID = $user->getUserIdByMobile($mgrMobile);
        }

        $config = new ConfigModel();  
        for ($i = 0; $i < count($class_ids); $i++) {
            if ($class_ids[$i]) {
                $class_info = explode(';', $class_ids[$i]);
                $plan_year = $class_info[0];
                $plan_season = $class_info[1];
                $plan_class_id = $class_info[2];
                $model = new Common();
                $list = $model->query("call programDrawConfirmDetail('".$plan_year."','".$plan_season."','".$plan_class_id."','".$userInfo['mobile']."');");
                
                // 如果自己是助手查询辅导员负责的记录
                $relModel = new AssistantUserRelModel();
                $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
                $mgrMobile = $userInfo['mobile'];
                if($relInfo) {
                    $mgrMobile = $relInfo['userMobile'];
                    $Mgrlist = $model->query("call programDrawConfirmDetail('".$plan_year."','".$plan_season."','".$plan_class_id."','".$mgrMobile."');");

                    if(count($Mgrlist) > 0) {
                        foreach($Mgrlist[0] as $key => $val) {
                            $list[0][] = $val;
                        }
                    }
                }
 
                // 生成学生清单
                $students = [];
                // 生成学生清单
                if(count($list) > 0){
                    $students = $list[0];
                } 

                // 判断教材剩余数量是否满足要求
                $listLeft = $model->query("call programGetLeftNumByClassId('".$plan_year."','".$plan_season."','".$plan_class_id."','".$mgrMobile."');");
                
                if(count($listLeft) > 0 &&  // 有此班级信息
                    $listLeft[0][0]['plan_class_id'] == $plan_class_id &&   
                    $listLeft[0][0]['syrs'] >= count($students) &&           // 剩余发放数大于申请人数
                    count($students) > 0) {        // 申请人数大于0 
                        
                    $id = ''; 
                    // 有申请记录的，需要处理申请状态
                    for ($j = 0; $j < count($students); $j++) {
                        if($students[$j]['applyDetailId'] != '') {
                            $id = $id . ',' . $students[$j]['applyDetailId'];
                        }
                    }
    
                    if (substr($id, 0, 1) == ',') {
                        $id = substr($id, 1);
                    }

                    Db::startTrans();
                    // 批量更新
                    $where = [];
                    $where[] = ['id', 'in', $id];
                    $bookApplyDetail = new BookApplyDetailModel();
                    $ret = $bookApplyDetail->save(['is_qs' => 1], $where);
                    if (!$ret) {
                        $result['status'] = false;
                        $result['msg'] = '签收提交失败，请重试1';
                        Db::rollback();
                        return $result;
                    }
                    
                    $bookDraw = new BookDrawModel();
                    $iData=[];
                    for ($j = 0; $j < count($students); $j++) {
                            // 增加领取记录
                        $iData[] = [
                            'xh'                => $students[$j]['xh'],
                            'draw_school_id'    => '',
                            'draw_institute_id' => '',
                            'draw_dep_id'       => $students[$j]['plan_dep_id'],
                            'draw_specialty_id' => $students[$j]['plan_specialty_id'],
                            'draw_class_id'     => $students[$j]['plan_class_id'],
                            'draw_grade'        => $students[$j]['plan_grade'],
                            'draw_dir'          => $students[$j]['plan_dir'],
                            'draw_year'         => $plan_year,
                            'draw_season'       => $plan_season,
                            'draw_operid'       => $this->userId,
                            'draw_date'         => time(),
                            'draw_remark'       => '', 
                            'draw_mgrid'        => $mgrID
                        ];
                    }
                        
                    if (!$bookDraw->saveAll($iData)) {
                        $result['status'] = false;
                        $result['msg'] = '签收提交失败，请重试2';
                        Db::rollback();
                        return $result;
                    }
                
                    Db::commit(); 
                }
                else {
                    $result['status'] = false;
                    $result['msg'] = '部分班级剩余教材数量不足'; 
                } 
            }
        }
        
        return $result;
    }

    /**
     * 个人签收
     * @return array
     */
    public function bookDetailDraw()
    { 
        $result = [
            'status' => true,
            'msg'    => '签收成功',
            'data'   => [],
        ];

        $xh  = input('param.xh', '');                               // 学号
        $id  = input('param.id', '');                               // ID
        $plan_year  = input('param.plan_year', '');                 // 年度
        $plan_season  = input('param.plan_season', '');             // 季度
        $plan_dep_id  = input('param.plan_dep_id', '');             // 部门ID
        $plan_specialty_id  = input('param.plan_specialty_id', ''); // 专业ID
        $plan_class_id  = input('param.plan_class_id', '');         // 班级ID
        $plan_dir  = input('param.plan_dir', '');                   // 方向ID

        // 查询学生清单  
        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId); 
        $relModel = new AssistantUserRelModel();
        $relInfo = $relModel->where(['assistantUserMobile' => $userInfo['mobile']])->find();
        $mgrID = $this->userId;
        $mgrMobile = $userInfo['mobile'];
        if($relInfo) {
            $mgrMobile = $relInfo['userMobile'];
            $mgrID = $user->getUserIdByMobile($mgrMobile);
        }

        $xhList = explode(',', $xh);
        $config = new ConfigModel();
        $bookApplyDetail = new BookApplyDetailModel();
         
        $model = new Common();
        // 判断教材剩余数量是否满足要求
        $listLeft = $model->query("call programGetLeftNumByClassId('".$plan_year."','".$plan_season."','".$plan_class_id."','".$mgrMobile."');");
        
        if(count($listLeft) > 0 &&  // 有此班级信息
            $listLeft[0][0]['plan_class_id'] == $plan_class_id &&   
            $listLeft[0][0]['syrs'] >= count($xhList) &&           // 剩余发放数大于申请人数
            count($xhList) > 0) {        // 申请人数大于0 
                
            // 判断当前学生清单是否与申请列表匹配
            if($listLeft[0][0]['batchNum'] > 0) {
                $applyXhList = $bookApplyDetail->getApplyXhList($plan_class_id); 
                foreach($xhList as $val) {
                    if(!in_array($val, $applyXhList)) {
                        $result['status'] = false;
                        $result['msg'] = $val.'不属于申请列表成员';
                        return $result;
                    }
                }
            }

            $bookDraw = new BookDrawModel();

            $whereExist = []; 
            $whereExist[] = ['xh', 'eq', $xhList[0]];
            $whereExist[] = ['draw_year', 'eq', $plan_year];
            $whereExist[] = ['draw_season', 'eq', $plan_season];
            $exist = $bookDraw->where($whereExist)->find(); 
            if(!$exist){
                Db::startTrans();
                // 批量更新
                $where[] = ['id', 'in', $id];
                if (!$bookApplyDetail->save(['is_qs' => 1], $where)) {
                    $result['status'] = false;
                    $result['msg'] = '签收提交失败，请重试';
                    Db::rollback();
                    return $result;
                }
                 
                
                $studentApplyInfo = $bookApplyDetail->getStudentApplyInfo($plan_year, $plan_season, $xhList[0]);
                $grade = '';
                if($studentApplyInfo) {
                    $grade = $studentApplyInfo['grade'];
                }

                $iData=[];
                for ($i = 0; $i < count($xhList); $i++) {
                        // 增加领取记录
                    $iData[] = [
                        'xh'                => $xhList[$i],
                        'draw_school_id'    => '',
                        'draw_institute_id' => '',
                        'draw_dep_id'       => $plan_dep_id,
                        'draw_specialty_id' => $plan_specialty_id,
                        'draw_class_id'     => $plan_class_id,
                        'draw_grade'        => $grade,
                        'draw_dir'          => $plan_dir,
                        'draw_year'         => $plan_year,
                        'draw_season'       => $plan_season,
                        'draw_operid'       => $this->userId,
                        'draw_date'         => time(),
                        'draw_remark'       => '', 
                        'draw_mgrid'        => $mgrID
                    ];
                }
                
                if (!$bookDraw->saveAll($iData)) {
                    $result['status'] = false;
                    $result['msg'] = '签收提交失败，请重试';
                    Db::rollback();
                    return $result;
                }
        
                Db::commit();  
                // 设置账表状态
                // $whereUpdate[] = ['xh', 'in', $xhList];
                // $whereUpdate[] = ['year', 'eq', $config->getYear()];
                // $whereUpdate[] = ['season', 'eq', $config->getSeason()];
                // $bookAccountModel = new BookAccountModel();
                // $bookAccountModel->save(['status'=>0], $whereUpdate);
            }
        } else {
            $result['status'] = false;
            $result['msg'] = '班级剩余教材数量不足'; 
            return $result;
        }
        
        return $result;
    }

    /**
     * 转让教材
     * @return array
     */
    public function changeStudent()
    { 
        $result = [
            'status' => true,
            'msg'    => '转让成功',
            'data'   => [],
        ];

        $srcXh  = input('param.srcXh', '');                              // 源学号
        $destXh  = input('param.destXh', '');                            // 目标学号
        $classId  = input('param.classId', '');                            // 目标学号

        $model = new Common();
        // 判断教材剩余数量是否满足要求
        $model->query("call changeStudent('".$srcXh."','".$destXh."','".$classId."');");
        
        return $result;
    } 

    /**
     * 转让教材
     * @return array
     */
    public function exportExcel()
    { 
        $id = input('param.id', '');

        $plan_class_id  = input('param.plan_class_id', '');     // 搜索关键字

        $user = new UserModel();
        $userInfo = $user->getUserInfo($this->userId);
        
        $model = new Common();
        // 查询自己负责的记录
        $list = $model->query("call programApplyLogDetail('".$id."');");
       
        $url = '';
        // 查询导出内容
        $template = config('zlserver.applylog_export_templete');     //使用模板
        $objPHPExcel = \PHPExcel_IOFactory::load($template);     //加载excel文件,设置模板 
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);  //设置保存版本格式  
        
        //接下来就是写数据到表格里面去  
        $objActSheet = $objPHPExcel->getActiveSheet();
        $i = 2;
        foreach ($list[0] as $key => $val) {
            //这里是设置单元格的内容  
            $objActSheet->setCellValue('A'.$i, $val['xh']); 
            $objActSheet->setCellValue('B'.$i, $val['xm']); 

            $i++;
        }
        
        $file_name = "apply_log-xls-" . date("YmdHis", time()) . ".xls";
        $generalPath = get_hash_dir($file_name);
        $filePath  = defined("FILE_PATH") ? FILE_PATH : ROOT_PATH . 'public' . DS . 'static' . DS . 'file' . $generalPath;
        if (!is_dir($filePath)) {
            @mkdirs($filePath, 0777, true);
        } 
        $fullFilePath = $filePath . $file_name;
        // 1.保存至本地Excel表格  
        $objWriter->save($fullFilePath);
              
        // 返回下载链接
        $url = "https://zlcw.zhongliansoft.com/static/file" . $generalPath . $file_name;

        $return_data = array(
            'status' => true,
            'msg'    => '导出成功',
            'url'    => $url
        );

        return $return_data;
    } 
    
}
